﻿using System.Net.WebSockets;
using System.Text;

namespace API.Middlewares
{
    public class WebSocketManager : IWebSocketManager
    {
        public readonly List<WebSocket> _clients;

        public WebSocketManager()
        {
            _clients = new List<WebSocket>();
        }
        // 实现获取所有开放状态的WebSocket客户端
        public IEnumerable<WebSocket> GetAllOpenClients()
        {
            return _clients.Where(client => client.State == WebSocketState.Open);
        }

        public async Task AddClientAsync(WebSocket socket)
        {
            _clients.Add((socket));
        }

        public async Task RemoveClientAsync(WebSocket socket)
        {
            //var clientToRemove = _clients.FirstOrDefault(c => c.Socket == socket);
            //if (clientToRemove != default)
            //{
            _clients.Remove(socket);
            //}
        }

        public async Task SendToAllAsync(string message)
        {
            var tasks = _clients.Select(async (client) =>
            {
                if (client.State == WebSocketState.Open)
                {
                    await client.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
                }
            });

            await Task.WhenAll(tasks);
        }

        public async Task SendToClientAsync(string clientId, string message)
        {
            //var client = _clients.FirstOrDefault(c => c.ClientId == clientId && c.Socket.State == WebSocketState.Open);
            //if (client != default)
            //{
            //    await client.Socket.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
            //}
        }
    }
}
